<template>
    <div class="pageContainer">
        <el-container class="bg-white rounded-lg">
            <el-header class="flex items-center justify-between" style="border-bottom: 1px solid #eeeeee;">
                <el-button type="primary" @click="onAdd">新增</el-button>
                <el-button type="primary" text @click="onSearch">
                    <el-icon :size="20">
                        <Refresh />
                    </el-icon>
                </el-button>
            </el-header>
            <el-container>
                <div class="w-full text-gray-500 p-2">
                    <el-tree :data="tableData" :props="{label:'name', value:'id', children:'child'}" node-key="id"
                        :default-expanded-keys="defaultExpandKyes" @node-expand="onNodeExpand" @node-collapse="onNodeCollapse">
                        <template #default="{ node, data }">
                            <div class="flex items-center w-full">
                                <el-tag size="small" :type="data.menu ? 'primary' : 'info'">{{ data.menu ? '菜单' : '权限'
                                    }}</el-tag>
                                <el-icon class="ml-2" :size="16">
                                    <component :is="data.icon || 'Operation'" />
                                </el-icon>
                                <span class="ml-2">{{ data.name }}</span>
                                <div class="ml-auto flex items-center justify-center text-sm">
                                    <el-switch v-model="data.status" :active-value="1"
                                        :inactive-value="0" @change="onStatusChange(data.id, $event)"></el-switch>
                                    <el-button link type="primary" @click.stop="onEdit(data)" class="ml-2">修改</el-button>
                                    <el-popconfirm title="确定删除该管理员吗？" @confirm.stop="onDelete(data)">
                                        <template #reference>
                                            <el-button type="primary" link class="mx-2" @click.stop>删除</el-button>
                                        </template>
                                    </el-popconfirm>
                                </div>
                            </div>
                        </template>
                    </el-tree>
                </div>
            </el-container>
        </el-container>
        <FormDrawer ref="drawerRef" :title="drawerTitle" @submit="onSubmit">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="100">
                <el-form-item label="上级菜单" prop="rule_id">
                    <el-cascader :options="options" :props="cascaderProps" placeholder="顶级节点" v-model="form.rule_id" clearable />
                </el-form-item>
                <el-form-item label="菜单/规则" prop="menu">
                    <el-radio-group v-model="form.menu">
                        <el-radio :value="1">菜单</el-radio>
                        <el-radio :value="0">规则</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="菜单名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入菜单名称" clearable />
                </el-form-item>
                <div class="flex items-center justify-start" v-if="form.menu">
                    <el-form-item label="图标" prop="icon" >
                        <IconSelector v-model="form.icon"/>
                    </el-form-item>
                    <el-form-item label="前端路由" prop="frontpath">
                        <el-input v-model="form.frontpath" placeholder="请输入前端路由" clearable />
                    </el-form-item>
                </div>
                <div class="flex items-center justify-start" v-else>
                    <el-form-item label="请求方式" prop="method">
                        <el-select v-model="form.method" placeholder="请求方式：GET/POST/PUT/DELETE" style="width: 100px">
                            <el-option :key="1" label="GET" value="GET" />
                            <el-option :key="2" label="POST" value="POST" />
                            <el-option :key="3" label="PUT" value="PUT" />
                            <el-option :key="4" label="DELETE" value="DELETE" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="接口" prop="condition">
                        <el-input v-model="form.condition" placeholder="由后端提供的接口别名" clearable />
                    </el-form-item>
                </div>
                <el-form-item label="状态" prop="status">
                    <el-switch v-model="form.status" :active-value="1" :inactive-value="0" size="small" />
                </el-form-item>
                <el-form-item label="排序" prop="order">
                    <el-input-number v-model="form.order" :min="1" :max="1000" />
                </el-form-item>
            </el-form>
        </FormDrawer>
    </div>
</template>
<script setup>
import { getRuleTree, addRule, updateRuleById, deleteRuleById, UpateRuleStatusById } from '../../api/rule'
import { toast, openFullScreenLoading, closeFullScreenLoading } from '../../composables/util'
import { ref, reactive, onMounted } from 'vue'
import { useTableSearch, useForm } from '../../composables/common'
import FormDrawer from '../../components/FormDrawer.vue'
import IconSelector from '../../components/IconSelector.vue'


// 查询相关
// 定义查询表单
const searchform = reactive({
    keyword: "",
})

// 定义清除查询条件的表单
const clearSearchform = () => {
    searchform.keyword = ''
}

// 上级菜单选项
const options = ref([])

const cascaderProps =  {
    checkStrictly: true, 
    children:'child'
}



const defaultExpandKyes = ref([])

// 查询数据成功后的回调，可以不用定义
const onGetDataSucceed = (res) => {
    // 保存当前展开的keys
    const currentExpanded = [...defaultExpandKyes.value]
    // 更新数据
    addColumnForCascade(res.data.rules)
    options.value = res.data.rules
    // 合并新的第一级菜单id和当前展开的keys
    defaultExpandKyes.value = [
        ...new Set([
            ...res.data.list.map(item => item.id),
            ...currentExpanded
        ])
    ]
}

const addColumnForCascade = (arr) => {
    arr.forEach(item=>{
        item.value = item.id
        item.label = item.name
        if(item.child && item.child.length > 0) {
            addColumnForCascade(item.child)
        }
    })
    
}



const {
    tableRowClassName,
    onSearch,
    getData,
    onClearSearch,
    onPageChange,
    currentPage,
    tableData,
    totalCount,
    limit
} = useTableSearch({
    searchform,
    getTableList: getRuleTree,
    clearSearchform,
    onGetDataSucceed // 非必须
})

const onStatusChange = (id, status) => {
    const loading = openFullScreenLoading()
    UpateRuleStatusById(id, status).then(res => {
        toast("修改菜单状态成功")
    }).finally(() => {
        closeFullScreenLoading(loading)
    })
}

const onNodeExpand = (obj, node, arr) => {
    if (!defaultExpandKyes.value.includes(obj.id)) {
        defaultExpandKyes.value.push(obj.id)
    }
    // console.log(defaultExpandKyes.value)
}

const onNodeCollapse = (obj, node, arr) => {
    const index = defaultExpandKyes.value.indexOf(obj.id)
    if (index > -1) {
        defaultExpandKyes.value.splice(index, 1)
    }
    // console.log(defaultExpandKyes.value)
}


// 表单,注意表单一定需要一个id字段
const form = reactive({
    id: null,
    rule_id: 0,
    menu: 1,
    name: '',
    condition: '',
    method: '',
    status: 0,
    order: 20,
    icon: '',
    frontpath: ''
})
// 表单规则
const rules = reactive({
    rule_id: [{ required: true, message: '上级菜单不能为空', trigger: 'blur' },
        // {
        //     validator: (rule, value, callback) => {
        //         // 检查值是否为 0
        //         if (value === 0) {
        //             callback(new Error('上级菜单不能为空'));
        //         } else {
        //             callback();
        //         }
        //     },
        //     trigger: 'blur' // 触发验证的时机，这里设置为失去焦点时
        // }
    ],
    name: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
    condition: [{ required: true, message: '后端规则不能为空', trigger: 'blur' }],
    method: [{ required: true, message: '请求方式不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
    order: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
    icon: [{ required: true, message: '图标不能为空', trigger: 'blur' }]
})

const {
    formRef,
    drawerRef,
    drawerTitle,
    onAdd,
    onEdit,
    onDelete,
    onSubmit
} = useForm({
    title: '管理员', // 功能名称
    form, // form表单，必须
    tableData, // 表单数据来源
    getData, // 更新表单数据接口
    add: addRule, // 新增接口
    update: updateRuleById, // 修改接口
    delete: deleteRuleById // 删除接口
})



</script>
<style scoped>
:deep(.el-tree-node__content)
{
  line-height: 40px; /* 设置行高 */
  height: 40px; /* 通常设置与行高相同以确保内容垂直居中 */
}
</style>
